package com.wugh.fast.kernel.util;


import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author WUGH
 * @date 2018/5/24
 */
public class HttpUtils {

    private HttpUtils() {
    }

    /**
     * 从request获取登录的IP
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 判断是否为ajax请求
     * <pre>
     *     判断规则:
     *      1.如果接受参数支持json格式,则是ajax请求
     *      2.如果请求头X-Requested-With的值为XMLHttpRequest 则是ajax请求
     * </pre>
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        if (StringUtils.contains(request.getHeader("accept"), "application/json") || Objects.equals(request.getHeader("X-Requested-With"), "XMLHttpRequest")) {
            return true;
        }
        return false;
    }

    public static void writeJSON(HttpServletResponse response, Object data) {
        response.setContentType("application/json;charset=UTF-8");
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            IOUtils.write(JSON.toJSONString(data), outputStream, "utf-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
